import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import cookie from 'js-cookie'

//创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:8222',
    timeout: 30000
})

// 每次请求中使用拦截器，很直观的理解
service.interceptors.request.use(
    config => {
        //debugger
        if (cookie.get('guli_token')) {
            // 4.把cookie中信息放到header中
            config.headers['token'] = cookie.get('guli_token')
        }
        return config
    },
    error => {
        return Promise.reject(error.response)   // 返回接口返回的错误信息
    }
)

service.interceptors.response.use(
    response => {
        if (response.data.code === 28004) {
            window.location.href = "/login";
            return
        } else {
            if (response.data.code !== 20000) {
                //25000：订单支付中，不做任何提示
                if (response.data.code != 25000) {
                    Message({
                        message: response.data.message || 'error',
                        type: 'error',
                        duration: 5 * 1000
                    })
                }
            }else{
                return response;
            }
        }
    },
    error=>{
        return Promise.reject(error.response)   // 返回接口返回的错误信息
    }
)

export default service